const Service = require('egg').Service;
const seq = require('sequelize');
class UserService extends Service {

    // 签到列表
    async signList({ pageIndex = 0, pageSize = 10 }) {
        var pageIndex = pageIndex * 1 * pageSize;
        var pageSize = pageSize * 1;
        const options = {
            offset: pageIndex,
            limit: pageSize,
            attributes: ['id', 'name', 'num', 'sign', 'bless'],
            order: [['sign', 'DESC']],
        };
        return this.ctx.model.User.findAndCountAll(options);
    }
    // 签到
    async sign(post) {
        console.log("==============" + JSON.stringify(post));
        const options = {
            where: {
                name: post.name,
                num: post.num
            },
            attributes: ['id', 'name', 'num', 'sign', 'bless']
        };
        const user = await this.ctx.model.User.findOne(options);
        // 判断用户是否存在
        if (!user) {
            this.ctx.throw(500, '没有该员工信息');
        }
        // 判断签到状态
        if (user.sign) {
            this.ctx.throw(500, '亲，您已经签到过了哦~');
        }
        return user.update({ login: true, sign: true, bless: post.bless });
    }



    // 用户列表
    async list({ pageIndex = 0, pageSize = 10 }) {
        var pageIndex = pageIndex * 1 * pageSize;
        var pageSize = pageSize * 1;
        const options = {
            where: {

            },
            offset: pageIndex,
            limit: 2,
            attributes: ['id', 'name', 'num'],
            order: [
                this.ctx.model.random(),
                ['sign', 'DESC']
            ]
        };
        return this.ctx.model.User.findAndCountAll(options);



        // console.log(this.app.Sequelize);

        // return {
        //     msg: "1234"
        // }
    }

    // 用户详情
    async find(id) {
        const user = await this.ctx.model.User.findById(id);
        if (!user) {
            this.ctx.throw(500, '查找的用户信息不存在');
        }
        return user;
    }

    // 添加用户
    async create(data) {
        const options = {
            where: {
                name: data.name,
                num: data.num
            }
        };
        const user = await this.ctx.model.User.findOne(options);
        if (user) {
            this.ctx.throw(500, "改员工已存在");
        }
        return this.ctx.model.User.create(data);
    }
    // 编辑节目
    async update(data) {
        const user = await this.ctx.model.User.findById(data.id);
        if (!user) {
            this.ctx.throw(500, "更新员工信息失败");
        }
        return user.updateAttributes(data);
    }

    // 删除用户信息
    async del(id) {
        const user = await this.ctx.model.User.findById(id);

        if (!user) {
            this.ctx.throw(500, '删除的用户信息不存在');
        }
        return user.destroy();
    }

}
module.exports = UserService;